//
//  BNTabBar.swift
//  BNWeiBo
//
//  Created by ba.o0 on 16/8/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//2.1
//声明协议 需要继承NSObjectProtocol
protocol BNTabBarDelegate:NSObjectProtocol{
    //声明方法
    func tabBarButtonClick()
}

class BNTabBar: UITabBar {
    //2.2
    //声明一个代理
    weak var BNDelegate:BNTabBarDelegate?
    
    //3.0
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    //纯代码标识 -- 自动生成
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 监听方法
    func buttonClick(){
        BNDelegate?.tabBarButtonClick()
    }
    
    //3.1
    // MARK - 设置视图
    private func setupUI(){
        addSubview(composeButton)
    }
    
    //5.0
    //给子控件设置frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //子控件的宽度
        let childW = self.frame.width * 0.2
        var index:CGFloat = 0
        
        //遍历子控件
        for value in self.subviews{
         
        //NSClassFromString 通过字符串转 class
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                //设置frame
                value.frame.size.width = childW
                value.frame.origin.x = index * childW
                
                index++
                
                //为了给攥写按钮留位置
                if index == 2{
                    index++
                }
            }
            
        }
        //设置攥写按钮的frame
        composeButton.center.x = self.frame.width*0.5
        composeButton.center.y = self.frame.height*0.5
    }
    
    
    //3.2
    // MAKE: - 懒加载控件
    //撰写按钮
    private lazy var composeButton:UIButton = {
        
        let button = UIButton()
        
        //点击事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
   
        //设置背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)

        //设置图片
    button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
       
        button.setImage(UIImage(named:"tabbar_compose_icon_add"),forState: UIControlState.Normal)
        
        //4.0
        //屏幕适配
        button.sizeToFit()
        
        return button
    }()
    
}













